#include "handler.h"
#include "sql_writer.h"
#include <cstdlib>
#include <chrono>
#include <thread>

using kwdb::ingest::v1::WriteRequest;
using kwdb::ingest::v1::WriteResponse;

grpc::Status IngestServiceImpl::WriteBatch(grpc::ServerContext*,
                                           const WriteRequest* req,
                                           WriteResponse* resp) {
  // Inject delay for timeout testing
  if (const char* d = std::getenv("INJECT_DELAY_MS")) {
    int delay_ms = std::stoi(d);
    if (delay_ms > 0) {
      std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms));
    }
  }
  if (!req || req->points_size() == 0) {
    resp->set_code(1);
    resp->set_message("empty batch");
    resp->set_rows_written(0);
    return grpc::Status::OK;
  }

  const char* mode = std::getenv("INGEST_MODE");
  std::string ingest_mode = mode ? mode : "sql";

  if (ingest_mode == "sql") {
    std::string err;
    int64_t rows = write_points_sql(*req, &err);
    if (rows < 0) {
      resp->set_code(2);
      resp->set_message("sql writer failed: " + err);
      resp->set_rows_written(0);
    } else {
      resp->set_code(0);
      resp->set_message("ok");
      resp->set_rows_written(static_cast<uint64_t>(rows));
    }
    return grpc::Status::OK;
  }

  // �Y ILP !
  resp->set_code(3);
  resp->set_message("ILP writer not enabled");
  resp->set_rows_written(0);
  return grpc::Status::OK;
}